<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
    />
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
      .chart-container {
        transition: all 0.3s ease;
      }
      .gradient-bg {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }
      .glass-effect {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
      }
      @keyframes fadeInUp {
        from {
          opacity: 0;
          transform: translateY(20px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }
      .animate-fade-in-up {
        animation: fadeInUp 0.6s ease-out;
      }
    </style>
  </head>
  <body class="gradient-bg min-h-screen py-8 px-4">
    <div class="max-w-7xl mx-auto">
      <main class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        <div class="lg:col-span-3">
          <div class="bg-white rounded-2xl shadow-2xl p-6 chart-container">
            <div id="mainChart" class="h-96 w-full"></div>
          </div>
        </div>

        <div class="bg-white/10 glass-effect rounded-2xl p-6">
          <h2 class="text-2xl font-bold text-white mb-6">控制面板</h2>

          <div class="space-y-6">
            <div>
              <label class="block text-white font-medium mb-2">测试数据</label>
              <div class="space-y-3">
                <button
                  onclick="loadTestData('normal')"
                  class="w-full px-4 py-3 bg-white/20 hover:bg-white/30 text-white rounded-lg transition-all duration-300 flex items-center"
                >
                  <i class="fas fa-chart-line mr-3"></i>
                  <span>正常数据</span>
                </button>
                <button
                  onclick="loadTestData('longLabels')"
                  class="w-full px-4 py-3 bg-white/20 hover:bg-white/30 text-white rounded-lg transition-all duration-300 flex items-center"
                >
                  <i class="fas fa-text-width mr-3"></i>
                  <span>长标签数据</span>
                </button>
                <button
                  onclick="loadTestData('closeValues')"
                  class="w-full px-4 py-3 bg-white/20 hover:bg-white/30 text-white rounded-lg transition-all duration-300 flex items-center"
                >
                  <i class="fas fa-compress-alt mr-3"></i>
                  <span>相近数值数据</span>
                </button>
              </div>
            </div>

            <div class="bg-white/5 rounded-xl p-4">
              <h3 class="text-white font-medium mb-3">标签统计</h3>
              <div class="space-y-2 text-white/80 text-sm">
                <div class="flex justify-between">
                  <span>总标签数:</span>
                  <span id="totalLabels">0</span>
                </div>
                <div class="flex justify-between">
                  <span>调整标签数:</span>
                  <span id="adjustedLabels">0</span>
                </div>
                <div class="flex justify-between">
                  <span>重叠避免:</span>
                  <span id="overlapAvoided">0</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>

      <footer class="mt-12 bg-white/10 glass-effect rounded-2xl p-6">
        <h3 class="text-xl font-bold text-white mb-4">核心算法原理</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 text-white/80">
          <div>
            <h4 class="text-white font-medium mb-2">1. 标签长度检测</h4>
            <p>实时计算每个标签的文本长度，根据字符数量确定基准位置</p>
          </div>
          <div>
            <h4 class="text-white font-medium mb-2">2. 相邻标签距离检测</h4>
            <p>检测相邻柱体标签的垂直距离，识别潜在重叠风险</p>
          </div>
          <div>
            <h4 class="text-white font-medium mb-2">3. 动态位置调整</h4>
            <p>根据检测结果智能调整标签的垂直偏移量，确保清晰可读</p>
          </div>
          <div>
            <h4 class="text-white font-medium mb-2">4. 平滑过渡动画</h4>
            <p>标签位置变化时采用平滑动画，提升用户体验</p>
          </div>
        </div>
      </footer>
    </div>

    <script>
      let chart;

      // 智能标签位置计算函数
      function calculateLabelPositions(data) {
        const positions = [];
        const baseOffset = 15; // 基础偏移量
        const minDistance = 12; // 最小安全距离

        for (let i = 0; i < data.length; i++) {
          const value = data[i];
          const labelLength = value.toString().length;

          // 基础位置计算（考虑标签长度）
          let position = {
            value: value,
            baseY: baseOffset,
            actualY: baseOffset,
            needsAdjustment: false,
          };

          // 检查与相邻标签的距离
          if (i > 0) {
            const prevPosition = positions[i - 1];
            const distance = Math.abs(value - prevPosition.value);

            // 如果数值相近，调整标签位置避免重叠
            if (distance < minDistance) {
              position.actualY = prevPosition.actualY + minDistance;
              position.needsAdjustment = true;
            } else {
              //   position.actualY = baseOffset + (labelLength > 3 ? 15 : 0);
              //   position.actualY = minDistance;
              position.actualY = baseOffset;
            }
          }

          positions.push(position);
        }

        return positions;
      }

      // 初始化图表
      function initChart() {
        const chartDom = document.getElementById("mainChart");
        chart = echarts.init(chartDom);

        // 默认测试数据
        const testData = {
          categories: ["产品A", "产品B", "产品C", "产品D", "产品E"],
          values: [2891000, 2891000, 2891002, 1980000, 4560000],
        };

        renderChart(testData.categories, testData.values);

        window.addEventListener("resize", function () {
          chart.resize();
        });
      }

      // 渲染图表
      function renderChart(categories, values) {
        const labelPositions = calculateLabelPositions(values);
        console.log("labelPositions", labelPositions);
        // 统计信息
        const totalLabels = values.length;
        const adjustedLabels = labelPositions.filter(
          (p) => p.needsAdjustment
        ).length;
        const overlapAvoided = adjustedLabels;

        document.getElementById("totalLabels").textContent = totalLabels;
        document.getElementById("adjustedLabels").textContent = adjustedLabels;
        document.getElementById("overlapAvoided").textContent = overlapAvoided;

        const option = {
          title: {
            text: "产品销售数据统计",
            left: "center",
            textStyle: {
              color: "#2c3e50",
              fontSize: 18,
              fontWeight: "bold",
            },
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "10%",
            top: "15%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            data: categories,
            axisLabel: {
              interval: 0,
              rotate: 0,
              fontSize: 12,
              color: "#666",
            },
            axisLine: {
              lineStyle: {
                color: "#e0e0e0",
              },
            },
          },
          yAxis: {
            type: "value",
            name: "销售额（万元）",
            nameTextStyle: {
              fontSize: 12,
              color: "#666",
            },
            axisLine: {
              lineStyle: {
                color: "#e0e0e0",
              },
            },
            splitLine: {
              lineStyle: {
                color: "#f0f0f0",
              },
            },
          },
          series: [
            {
              name: "销售额",
              type: "bar",
              barWidth: "50%",
              barCategoryGap: "5%",
              data: values.map((value, index) => {
                const position = labelPositions[index];

                return {
                  value: value,
                  label: {
                    show: true,
                    position: [0, -position.actualY],
                    formatter: "{c}",
                    textStyle: {
                      color: position.needsAdjustment ? "#e74c3c" : "#2c3e50",
                      fontSize: 12,
                      fontWeight: "bold",
                      //   //   backgroundColor: "rgba(255,255,255,0.95)",
                      //   padding: [4, 8],
                      //   borderRadius: 6,
                      //   borderColor: position.needsAdjustment
                      //     ? "#e74c3c"
                      //     : "#e0e0e0",
                      //   borderWidth: 1,
                    },
                  },
                };
              }),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#83bff6" },
                  { offset: 1, color: "#188df0" },
                ]),
                borderRadius: [4, 4, 0, 0],
              },
              emphasis: {
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#2378f7" },
                    { offset: 1, color: "#83bff6" },
                  ]),
                },
              },
            },
          ],
        };

        chart.setOption(option);
      }

      // 加载测试数据
      function loadTestData(type) {
        let categories, values;

        switch (type) {
          case "normal":
            categories = ["产品A", "产品B", "产品C", "产品D", "产品E"];
            values = [156, 289, 342, 198, 456];
            break;
          case "longLabels":
            categories = [
              "产品A-第一季度",
              "产品B-第二季度",
              "产品C-第三季度",
              "产品D-第四季度",
              "产品E-年度总结",
            ];
            values = [120, 118, 122, 119, 121];
            break;
          case "closeValues":
            categories = ["产品A", "产品B", "产品C", "产品D", "产品E"];
            values = [250, 248, 252, 249, 251];
            break;
        }

        renderChart(categories, values);
      }

      // 页面加载完成后初始化图表
      document.addEventListener("DOMContentLoaded", function () {
        initChart();
      });
    </script>
  </body>
</html>
